<?php

namespace App\Http\Controllers;

use App\Models\File;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class FileController extends Controller
{
    public function index(Request $request)
    {
        $query = new File();
        if ($request->input('keyword')) {
            $query = $query->where('name', 'like', '%' . $request->input('keyword') . '%');
        }
        $obj = $query->orderBy('created_at', 'desc')->paginate($request->input('page_size', 25));
        return $this->response($obj);
    }

    public function store(Request $request, File $obj)
    {
        $file = $request->file('file');
        $path = Storage::disk('public')->putFile('file/' . date("Ymd"), $file);
        $obj->name = $file->getClientOriginalName();
        $obj->extension = $file->extension();
        $obj->url = Storage::disk('public')->url($path);;
        $obj->save();
        return $this->response();
    }

    public function update($id, Request $request)
    {
        $obj = File::where('id', $id)->first();
        $obj->name = $request->input('name');
        $obj->save();
        return $this->response();
    }

    public function destroy($id)
    {
        $obj = File::find($id);
        Storage::disk('public')->delete(str_replace('/storage/', "", $obj->url));
        $obj->delete();
        return $this->response();
    }
}
